import { createSlice } from '@reduxjs/toolkit'
import type { AppThunk } from '@/store'
import { userLoginApi } from '@/services/userApi'
import storage from '@/utils/storage'

const userSlice = createSlice({
  name: 'user',
  initialState: {
    userinfo: {
      id: 0,
      username: '',
      token: '',
      roleid: 0,
      routes: [],
      btns: []
    }
  } as IUserType.IState,
  reducers: {
    userLogoutReducer(state) {
      state.userinfo = {
        id: 0,
        username: '',
        token: '',
        roleid: 0,
        routes: [],
        btns: []
      }
      storage().remove('user')
    },
    setUserInfo(state, { payload }: { payload: IUserType.ILoginResult }) {
      state.userinfo = payload
      storage().set('user', payload)
    },
    setBtns(state, { payload }: { payload: string[] }) {
      state.userinfo.btns = payload
    }
  }
})

export const { setUserInfo, userLogoutReducer, setBtns } = userSlice.actions

// 中间件
// 异步请求，带有返回值
export const userLoginAction =
  (userData: IUserType.ILoginForm): AppThunk<Promise<number>> =>
  async (dispatch) => {
    let ret = await userLoginApi(userData)
    if (ret.code == 0) {
      dispatch(setUserInfo(ret.data))
    }
    return ret.code
  }

export default userSlice.reducer
